package com.da.web.sys_role.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.da.web.sys_menu.entity.MakeTree;
import com.da.web.sys_menu.entity.SysMenu;
import com.da.web.sys_menu.service.SysMenuService;
import com.da.web.sys_role.entity.AssignParm;
import com.da.web.sys_role.entity.AssignVo;
import com.da.web.sys_role.entity.RoleParm;
import com.da.web.sys_role.entity.SysRole;
import com.da.web.sys_role.mapper.SysRoleMapper;
import com.da.web.sys_role.service.SysRoleService;
import com.da.web.sys_user.entity.SysUser;
import com.da.web.sys_user.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author da
 * @time 2023/12/1 下午 4:25
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public IPage<SysRole> list(RoleParm parm) {
        //构造 分页对象
        IPage<SysRole> page = new Page<>();
        page.setCurrent(parm.getCurrentPage());
        page.setSize(parm.getPageSize());
        //构造查询条件
        QueryWrapper<SysRole> query = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(parm.getRoleName())) {
            query.lambda().like(SysRole::getRoleName, parm.getRoleName());
        }
        return this.baseMapper.selectPage(page, query);
    }

    @Override
    public AssignVo getAssignShow(AssignParm parm) {
        SysUser user = sysUserService.getById(parm.getUserId());
        List<SysMenu> menuList;
        if (user.getIsAdmin().equals("1")) {
            //如果是超级管理员,就有所有的菜单权限
            QueryWrapper<SysMenu> query = new QueryWrapper<>();
            query.lambda().orderByAsc(SysMenu::getOrderNum);
            menuList = sysMenuService.list(query);
        } else {
            //如果不是超级管理员就需要按照自己的id来查询对应的菜单
            menuList = sysMenuService.getMenuByUserId(user.getUserId());
        }
        //组装菜单树
        menuList = MakeTree.makeMenuTree(menuList, 0L);
        //查询角色原来的菜单权限
        List<SysMenu> menuByRoleId = sysMenuService.getMenuByRoleId(parm.getRoleId());
        //过滤出id
        List<Long> ids = new ArrayList<>();
        Optional.ofNullable(menuByRoleId).orElse(new ArrayList<>())
                .stream()
                .filter(Objects::nonNull)
                .forEach(i -> ids.add(i.getMenuId()));
        //组装返回值
        AssignVo vo = new AssignVo();
        vo.setMenuList(menuList);
        vo.setCheckList(ids.toArray());
        return vo;
    }
}
